package com.sword.config;

import com.sword.pojo.system.Employee;
import com.sword.service.impl.system.EmployeeServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    //授权
    @Autowired
    EmployeeServiceImpl employeeService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthorizationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //连接数据库
        Employee employee = employeeService.queryEmployeeById(userToken.getUsername());
        if(employee == null){
            return null;
        }
        Subject User = SecurityUtils.getSubject();
        Session session = User.getSession();
        session.setAttribute("loginUser",userToken.getUsername());
        String loginUser = (String) session.getAttribute("loginUser");
        return new SimpleAuthenticationInfo("",employee.getPassword(),"");
    }
}
